<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>组件生命周期初识</title>
</head>
<body>
<div id="life"></div>

<script src="js/react.development.js" crossorigin></script>
<script src="js/react-dom.development.js" crossorigin></script>
<script src="js/babel.js"></script>
<script type="text/babel">

    class Life extends React.Component {

        state = {opacity:1}

        death = () => {
            // 卸载组件
            ReactDOM.unmountComponentAtNode(document.getElementById('life'))
        }

        // 组件完成挂载调用一次
        componentDidMount(){
            this.timer = setInterval( ()=>{
                let {opacity} = this.state
                opacity -= 0.1
                if (opacity <= 0) {
                    opacity =1
                }
                this.setState({opacity})
            },200 )
        }

        // 组件将要卸载调用
        componentWillUnmount(){
            // 清除定时器
            clearInterval(this.timer)
        }

        // 初始化渲染、状态更新调用
        render() {
            return (
                <div>
                    <h2 style={{opacity:this.state.opacity}}> This is a Title </h2>
                    <button onClick={this.death}> onClick</button>
                </div>
            )
        }
    }

    ReactDOM.render(<Life/>, document.getElementById('life'))
</script>
</body>
</html>